﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "common.h"
#include "addautoconnecttimespan.h"
#include <QSettings>
#include <QListWidget>
#include <QListWidgetItem>
#include <QContextMenuEvent>
#include <QEvent>
#include <QMenu>
#include <QWindowStateChangeEvent>
#include <QMessageBox>
#include <QDebug>
#include <QTime>
#include <QTimer>
#include <QTextCodec>
MainWindow::MainWindow(QMainWindow *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QTextCodec *codec = QTextCodec::codecForName("ansi");
    QTextCodec::setCodecForLocale(codec);
    init();


}

MainWindow::~MainWindow()
{

    delete ui;
    delete settings;
    delete systemTrayIcon;
    delete manager;


}

void MainWindow::usernameChanged()
{

    settings->setValue("username",ui->leUsername->text());
}

void MainWindow::passwordChanged()
{
    settings->setValue("password",ui->lePassword->text());
}

void MainWindow::addTime()
{
    AddAutoConnectTimeSpan w;
    if(QDialog::Accepted==w.exec())
    {
        autoConntectTime<<w.getRetstr();
        saveAutoConnectTime();
        freshAutoConnectTime();
    }
}

void MainWindow::deleteTimeSpan(int item)
{
    autoConntectTime.removeAt(item);
    saveAutoConnectTime();
    freshAutoConnectTime();
}

void MainWindow::init()
{
    //禁止最大化
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);

    //读取配置文件
    settings=new QSettings(ORGANIZATION);
    QString strUsername=settings->value("username","").toString();
    QString strPassword=settings->value("password","").toString();
    autoLogin=settings->value("autoLogin",false).toBool();
    startup=settings->value("startup",false).toBool();
    speedtype=settings->value("speedtype",0).toInt();
    setSpeedByType(speedtype);
    if(!autoLogin)ui->cmbSpeed->setEnabled(false);

    ui->leUsername->setText(strUsername);
    ui->lePassword->setText(strPassword);
    ui->cbAutoLogin->setChecked(autoLogin);
    ui->cbStartup->setChecked(startup);
    ui->cmbSpeed->setCurrentIndex(speedtype);



    //设置系统托盘
    systemTrayIcon=new QSystemTrayIcon(QIcon(":/picture/icon"));
    QMenu* menu=new QMenu(this);
    QAction* actionShow=menu->addAction(QStringLiteral("显示"));
    QAction* actionQuit=menu->addAction(QStringLiteral("退出"));
    systemTrayIcon->setContextMenu(menu);

    //设置网络管理器
    manager=new QNetworkAccessManager(this);


    //连接信号和槽
    connect(ui->leUsername,SIGNAL(editingFinished()),this,SLOT(usernameChanged()));
    connect(ui->lePassword,SIGNAL(editingFinished()),this,SLOT(passwordChanged()));
    connect(ui->btnAddTime,SIGNAL(clicked()),this,SLOT(addTime()));
    connect(ui->listWidget,SIGNAL(deleteItem(int)),this,SLOT(deleteTimeSpan(int)));
    connect(actionShow,SIGNAL(triggered()),this,SLOT(systemTrayIconShowAction()));
    connect(actionQuit,SIGNAL(triggered()),this,SLOT(systemTrayIconQuitAction()));
    connect(ui->cbStartup,SIGNAL(toggled(bool)),this,SLOT(startupChecked(bool)));
    connect(ui->cbAutoLogin,SIGNAL(toggled(bool)),this,SLOT(autoLoginChecked(bool)));
    connect(ui->btnLogin,SIGNAL(clicked()),this,SLOT(loginLogic()));
    connect(ui->btnLogout,SIGNAL(clicked()),this,SLOT(logoutLogic()));
    connect(ui->cmbSpeed,SIGNAL(currentIndexChanged(int)),this,SLOT(speedChanged(int)));

    //启动定时器
    startTimer(1000);

    //显示自动连接时段
    freshAutoConnectTime();



}

void MainWindow::setSpeedByType(int i)
{
    switch(i){
    case 0:interval=30;break;
    case 1:interval=60;break;
    case 2:interval=300;break;
    case 3:interval=600;break;
    case 4:interval=1800;break;
    case 5:interval=3600;break;
    default:break;
    }
}

int MainWindow::timeToInt(QTime time)
{
    return time.second()+time.minute()*60+time.hour()*3600;
}

bool MainWindow::checkCurrentRun(int i)
{
    bool ret=false;
    foreach(TimeSpan span,timeSpan)
    {
        if(i>span.start()&&i<span.end())
        {
            ret=true;
            break;
        }
    }
    return ret;
}

QList<TimeSpan> MainWindow::getTimeSpan(QStringList list)
{
    QString temp;
    QList<TimeSpan> ret;
    foreach(temp,list)
    {
        QStringList li=temp.split("-");
        int start=timeToInt(QTime::fromString(li[0],"hh:mm:ss"));
        int end=timeToInt(QTime::fromString(li[1],"hh:mm:ss"));
        TimeSpan span(start,end);
        ret.append(span);
    }
    return ret;
}

void MainWindow::changeEvent(QEvent *event)
{
    if(event->type()==QEvent::WindowStateChange)
    {
        if(windowState()==Qt::WindowMinimized)
        {
            hide();
        }
    }

}

void MainWindow::timerEvent(QTimerEvent *)
{
    int current=timeToInt(QTime::currentTime());
    if(current<lastLoginTime)lastLoginTime=current;
    run=checkCurrentRun(current);
    if(run&&tocnt==-1)
    {
        if(current-lastLoginTime>interval)
        {
            lastLoginTime=current;
            loginLogic();
        }
    }
    if(delay>0&&delay!=-1)
    {
        ui->btnLogin->setText(QStringLiteral("请等待%1s").arg(delay));
        ui->btnLogout->setText(QStringLiteral("请等待%1s").arg(delay));
        delay--;
    }else if(delay==0){
        ui->btnLogin->setText(QStringLiteral("登录"));
        ui->btnLogout->setText(QStringLiteral("注销"));
        ui->btnLogin->setEnabled(true);
        ui->btnLogout->setEnabled(true);
        delay=-1;
    }
    if(tocnt>0&&tocnt!=-1)
    {
        ui->lblDetail->setText(QStringLiteral("等待超时时间:%1s").arg(tocnt));
        tocnt--;
    }else if(tocnt==0){
        ui->lblDetail->setText(QStringLiteral("<div style='color:#800'>连接超时</div>"));
        ui->btnLogin->setEnabled(true);
        ui->btnLogout->setEnabled(true);
        tocnt=-1;
    }

}

void MainWindow::setAutoConntectTime(const QStringList &value)
{
    autoConntectTime = value;
}

QStringList MainWindow::getAutoConntectTime()
{
    return autoConntectTime;
}

void MainWindow::freshAutoConnectTime()
{
    autoConntectTime=settings->value("autoconnecttime").toStringList();
    timeSpan=getTimeSpan(autoConntectTime);
    ui->listWidget->clear();
    QString temp;
    int i=0;
    if(autoConntectTime.count()>0)
    {
        foreach(temp,autoConntectTime)
        {
            QString outstr=QString(" %1  ").arg(++i);
            QStringList li=temp.split("-");

            outstr+=li[0];
            outstr+="------>";
            outstr+=li[1];
            QListWidgetItem* item=new QListWidgetItem(outstr);
            item->setFont(QFont("SansMono",12));
            ui->listWidget->addItem(item);
        }
    }else{
        QListWidgetItem* item=new QListWidgetItem(QStringLiteral(AUTOTIMESPANHINT));
        item->setFont(QFont("SansMono",12));
        ui->listWidget->addItem(item);
    }
    if(autoLogin){
        lastLoginTime=timeToInt(QTime::currentTime());
        loginLogic();
    }
}

void MainWindow::saveAutoConnectTime()
{
    settings->setValue("autoconnecttime",autoConntectTime);
}



void MainWindow::systemTrayIconQuitAction()
{
    qApp->exit(0);
}

void MainWindow::systemTrayIconShowAction()
{
    show();
    setWindowState(Qt::WindowNoState);
}

void MainWindow::startupChecked(bool b)
{
    bool ret=false;
    if(b)
    {
#if defined(Q_OS_LINUX)
        ui->cbStartup->setChecked(false);
        QMessageBox::information(this,"提示","Linux 系统暂不支持开机启动");
        ret=false;
#elif defined(Q_OS_WIN)
        QString appName = QApplication::applicationName();

        QString appPath = QApplication::applicationFilePath();

        appPath = appPath.replace("/","\\");

        QSettings *reg=new QSettings(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                    QSettings::NativeFormat);

        QString val = reg->value(appName).toString();
        if(val != appPath)
            reg->setValue(appName,appPath);
        reg->deleteLater();
        ret=true;
#endif
    }
    else
    {
#if defined(Q_OS_LINUX)

        ret=true;
#elif defined(Q_OS_WIN)
        QString appName = QApplication::applicationName();
        QSettings *reg=new QSettings(
                    QString("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
                    QSettings::NativeFormat);
        reg->setValue(appName,"");
        reg->deleteLater();
        ret=false;
#endif
    }
    settings->setValue("startup",ret);
    ui->cbStartup->setChecked(ret);
}

void MainWindow::autoLoginChecked(bool b)
{
    bool ret=false;
    if(b)
    {
        ret=true;
        lastLoginTime=timeToInt(QTime::currentTime());

    }
    else
    {
        ret=false;

    }
    settings->setValue("autoLogin",ret);
    ui->cbAutoLogin->setChecked(ret);
    ui->cmbSpeed->setEnabled(ret);
    run=ret;
}

void MainWindow::loginLogic()
{
    ui->btnLogin->setEnabled(false);
    ui->btnLogout->setEnabled(false);
    tocnt=timeout;
    state=PREPARELOGIN;
    QNetworkRequest request;
    request.setUrl(QUrl("http://202.204.48.82"));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    QByteArray array;
    array.append(QString("DDDDD=%1").arg(ui->leUsername->text()));
    array.append(QString("&upass=%1").arg(ui->lePassword->text()));
    array.append(QString("&0MKKey=123456789"));
    reply = manager->post(request,array);
    connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(slotSslErrors(QList<QSslError>)));

}

void MainWindow::logoutLogic()
{
    ui->btnLogin->setEnabled(false);
    ui->btnLogout->setEnabled(false);

    state=PREPARELOGOUT;
    QNetworkRequest request;
    request.setUrl(QUrl("http://202.204.48.82/F.htm"));
    reply = manager->get(request);
    connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(slotSslErrors(QList<QSslError>)));
}

void MainWindow::slotReadyRead()
{
    qDebug()<<state;
    tocnt=-1;
    if(state==PREPARELOGIN)
    {
        QString s(reply->readAll());
        QRegExp reg("Msg=(\\d+);");
        int msg=-1;
        if (reg.indexIn(s) != -1)
        {
            msg=reg.cap(1).toInt();
            if(msg==1)
            {
                state=LOGINFAILED;
                reply->disconnect();
                reply->deleteLater();
                if(!autoLogin)
                    QMessageBox::critical(this,QStringLiteral("用户名或密码错误"),QStringLiteral("请检查用户名和密码是否输入正确"));
                else
                    ui->lblDetail->setText(QStringLiteral("<div style='color:#800'>用户名或密码错误,请检查用户名和密码是否输入正确</div>"));

            }
        }
        else
        {
            reply->disconnect();
            reply->deleteLater();
            state=LOGINSUCCESS;
            QNetworkRequest request;
            request.setUrl(QUrl("http://202.204.48.82/1.htm"));
            reply = manager->get(request);
            connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
            connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                    this, SLOT(slotError(QNetworkReply::NetworkError)));
            connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
                    this, SLOT(slotSslErrors(QList<QSslError>)));
        }
    }else if(state==LOGINSUCCESS){

        QString s(reply->readAll());
        QRegExp reg("uid='(\\w+)';");

        if (reg.indexIn(s) != -1)
        {
            QString tempUsername=reg.cap(1);
            if(tempUsername==ui->leUsername->text())
            {
                QRegExp reg2("time='(.*)';flow='(.*)';fsele=(?:.*);fee='(.*)';xsele");
                if(reg2.indexIn(s)!=-1)
                {
                    // int temp1=reg2.cap(1).trimmed().toInt();//访问次数
                    int temp2=reg2.cap(2).trimmed().toInt();//流量 K
                    int temp3=reg2.cap(3).trimmed().toInt();//余额 万分之一元

                    char unit[][3]={"KB","MB"};
                    int unitidx=0;
                    double flow=0;
                    if(temp2<1024)
                        flow=temp2;
                    else
                    {
                        flow=static_cast<double>(temp2)/1024;
                        unitidx=1;
                    }
                    double money;
                    money=static_cast<double>(temp3)/10000;

                    QString  detail="";
                    detail+="<div style='color:#008'>";
                    detail+=QStringLiteral("当前余额:%1元<br/>").arg(money,0,'f',1);
                    detail+=QStringLiteral("流量(V4):%1%2").arg(flow).arg(unit[unitidx]);
                    ui->lblDetail->setText(detail);
                    state=IDLE;
                    reply->disconnect();
                    reply->deleteLater();

                }
                else
                {
                    unknownError();
                }
            }
            else
            {
                unknownError();
            }
        }
        else
        {

            unknownError();
        }
        delay=3;

    }else if(state==PREPARELOGOUT)
    {
        QString s(reply->readAll());
        QRegExp reg("Msg=(\\d+);");
        int msg=-1;
        if (reg.indexIn(s) != -1)
        {
            msg=reg.cap(1).toInt();
            if(msg==14)
            {
                state=LOGOUTSUCCESS;
                reply->disconnect();
                reply->deleteLater();
                QString  detail="";
                detail+=QStringLiteral("<div style='color:#008'>注销成功</div>");
                ui->lblDetail->setText(detail);

            }else{
                //  unknownError();
            }
        }else{
            //  unknownError();
        }
        ui->btnLogin->setEnabled(true);
        ui->btnLogout->setEnabled(true);

    }
}

void MainWindow::slotError(QNetworkReply::NetworkError)
{
    tocnt=-1;
    reply->disconnect();
    reply->deleteLater();
    ui->btnLogin->setEnabled(true);
    ui->btnLogout->setEnabled(true);
    if(!autoLogin)
        QMessageBox::critical(this,QStringLiteral("错误"),QStringLiteral("网络连接失败"));
    else
        ui->lblDetail->setText(QStringLiteral("<div style='color:#800'>错误,网络连接失败</div>"));


}

void MainWindow::slotSslErrors(QList<QSslError>)
{
    //    tocnt=-1;
    //    reply->disconnect();
    //    reply->deleteLater();
    //    ui->btnLogin->setEnabled(true);
    //    ui->btnLogout->setEnabled(true);
    //    if(!autoLogin)
    //         QMessageBox::critical(this,QStringLiteral("错误"),QStringLiteral("网络连接失败 SSL认证错误（没有）"));
    //    else
    //        ui->lblDetail->setText(QStringLiteral("错误，网络连接失败 SSL认证错误（没有）"));


}

void MainWindow::unknownError()
{
    state=IDLE;
    reply->disconnect();
    reply->deleteLater();
    ui->btnLogin->setEnabled(true);
    ui->btnLogout->setEnabled(true);
    if(!autoLogin)
        QMessageBox::critical(this,QStringLiteral("错误"),QStringLiteral("未知错误"));
    else
        ui->lblDetail->setText(QStringLiteral("<div style='color:#800'>发生了未知错误</div>"));


}

void MainWindow::speedChanged(int i)
{
    settings->setValue("speedtype",i);
    setSpeedByType(i);
}
